<template>
  <div class="payment-container">
    <!-- 支付确认信息 -->
    <div v-if="showPaymentConfirm && !showQRCode" class="payment-confirm">
      <h2>确认支付</h2>
      <div class="payment-info">
        <div class="info-item">
          <span class="label">收款方：</span>
          <span class="value">{{ paymentInfo.groupName }}</span>
        </div>
        <div class="info-item">
          <span class="label">支付金额：</span>
          <span class="value amount">¥{{ paymentInfo.amount }}</span>
        </div>
        <div class="info-item">
          <span class="label">支付说明：</span>
          <span class="value">群费</span>
        </div>
      </div>
      <div class="confirm-actions">
        <button class="cancel-btn" @click="cancelPayment">取消</button>
        <button class="confirm-btn" @click="confirmPayment">确认支付</button>
      </div>
    </div>
    
    <!-- 支付方式选择 -->
    <div v-if="showPaymentMethodSelection" class="payment-method-selection">
      <h2>选择支付方式</h2>
      <div class="payment-methods">
        <div 
          v-for="method in availablePaymentMethods" 
          :key="method.id" 
          class="payment-method-item"
          :class="{ selected: selectedPaymentMethod === method.id }"
          @click="selectPaymentMethod(method.id)"
        >
          <div class="method-icon">{{ method.icon }}</div>
          <div class="method-name">{{ method.name }}</div>
          <div v-if="selectedPaymentMethod === method.id" class="selected-icon">✓</div>
        </div>
      </div>
      <div class="method-actions">
        <button class="cancel-btn" @click="cancelPaymentMethodSelection">取消</button>
        <button class="confirm-btn" @click="confirmPaymentMethod">确定</button>
      </div>
    </div>
    
    <!-- 验密界面 -->
    <div v-if="showPasswordVerification" class="password-verification">
      <h2>验证支付密码</h2>
      <div class="verification-info">
        <p>收款方：{{ paymentInfo.groupName }}</p>
        <p>金额：¥{{ paymentInfo.amount }}</p>
        <p>支付方式：{{ getSelectedPaymentMethodName() }}</p>
      </div>
      <div class="password-input-container">
        <input 
          type="password" 
          v-model="paymentPassword" 
          placeholder="请输入支付密码"
          @keyup.enter="verifyPaymentPassword"
        >
      </div>
      <div class="verification-actions">
        <button class="cancel-btn" @click="cancelPasswordVerification">取消</button>
        <button class="confirm-btn" @click="verifyPaymentPassword">确认支付</button>
      </div>
      <div class="verification-options">
        <button class="fingerprint-btn" @click="useFingerprintVerification">
          指纹/面容支付
        </button>
      </div>
    </div>
    
    <!-- 支付二维码区域 -->
    <div v-if="showQRCode" class="qr-code-wrapper">
      <canvas ref="qrCodeCanvas" width="200" height="200"></canvas>
      <p class="tip">请使用微信扫描二维码支付</p>
      <p class="expire-tip">二维码将在 {{ countDown }} 秒后过期</p>
      <div class="payment-details">
        <p>收款方：{{ paymentInfo.groupName }}</p>
        <p>金额：¥{{ paymentInfo.amount }}</p>
      </div>
    </div>
    
    <!-- 支付结果区域 - 修改为更接近微信支付的成功页面 -->
    <div v-if="paymentSuccess" class="wechat-success-page">
      <div class="success-icon-container">
        <i class="icon-success">✓</i>
      </div>
      <h2 class="success-title">支付成功</h2>
      <div class="success-info">
        <div class="payment-amount">¥{{ paymentInfo.amount }}</div>
        <div class="payment-merchant">
          <p>商户：{{ paymentInfo.groupName }}</p>
          <p>支付说明：群费</p>
          <p>交易时间：{{ formatCurrentTime() }}</p>
        </div>
        <div class="payment-method-info">
          <p>支付方式：{{ getSelectedPaymentMethodName() }}</p>
        </div>
      </div>
      <button class="complete-button" @click="completePayment">完成</button>
      <div class="order-detail-btn" @click="viewOrderDetails">查看订单详情</div>
    </div>
    
    <!-- 支付失败区域 -->
    <div v-if="paymentFailed" class="fail-message">
      <i class="icon-fail">✗</i>
      <p>支付失败，请重试</p>
      <button @click="retryPayment">重新支付</button>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-message">
      <p>加载中...</p>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode' // 使用qrcode库生成二维码
import { createWechatPayment, queryPaymentStatus } from '../api/payment' // 导入支付API

export default {
  name: 'WechatPayment',
  data() {
    return {
      paymentLink: '', // 微信支付的code_url
      showQRCode: false,
      showPaymentConfirm: true, // 显示支付确认界面
      showPaymentMethodSelection: false, // 显示支付方式选择
      showPasswordVerification: false, // 显示验密界面
      paymentSuccess: false,
      paymentFailed: false,
      countDown: 180, // 二维码有效期180秒
      checkPaymentInterval: null, // 轮询检查支付状态的定时器
      timer: null, // 倒计时定时器
      orderId: '', // 订单ID
      loading: false,
      paymentInfo: {
        groupName: '',
        amount: 0,
        groupId: ''
      },
      availablePaymentMethods: [
        { id: 'wechat_balance', name: '微信零钱', icon: '' },
        { id: 'bank_card_1', name: '招商银行储蓄卡', icon: '' },
        { id: 'bank_card_2', name: '建设银行信用卡', icon: '' }
      ], // 可用支付方式
      selectedPaymentMethod: 'wechat_balance', // 默认选择微信零钱
      paymentPassword: '' // 支付密码
    }
  },
  
  mounted() {
    // 从路由参数中获取支付信息
    this.paymentInfo.groupName = this.$route.query.groupName || '金金铲铲群'
    this.paymentInfo.amount = Number(this.$route.query.amount) || 5
    this.paymentInfo.groupId = this.$route.query.groupId || 'default-group-id'
    this.orderId = this.$route.query.orderId || ''
    
    // 获取商户返回URL（从路由参数或配置中）
    this.merchantReturnUrl = this.$route.query.returnUrl || 'https://your-merchant-website.com/order-result'
  },
  
  beforeUnmount() {
    // 组件销毁时清除定时器
    if (this.checkPaymentInterval) {
      clearInterval(this.checkPaymentInterval)
    }
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  
  methods: {
    // 取消支付
    cancelPayment() {
      this.$router.back()
    },
    
    // 确认支付 - 修改为显示支付方式选择
    confirmPayment() {
      this.showPaymentConfirm = false
      this.showPaymentMethodSelection = true
    },
    
    // 选择支付方式
    selectPaymentMethod(methodId) {
      this.selectedPaymentMethod = methodId
    },
    
    // 确认支付方式，进入验密界面
    confirmPaymentMethod() {
      this.showPaymentMethodSelection = false
      this.showPasswordVerification = true
      this.paymentPassword = '' // 清空密码输入框
    },
    
    // 取消支付方式选择
    cancelPaymentMethodSelection() {
      this.showPaymentMethodSelection = false
      this.showPaymentConfirm = true
    },
    
    // 取消验密
    cancelPasswordVerification() {
      this.showPasswordVerification = false
      this.showPaymentMethodSelection = true
      this.paymentPassword = ''
    },
    
    // 获取选中的支付方式名称
    getSelectedPaymentMethodName() {
      const method = this.availablePaymentMethods.find(m => m.id === this.selectedPaymentMethod)
      return method ? method.name : ''
    },
    
    // 使用指纹/面容支付
    useFingerprintVerification() {
      // 模拟指纹验证
      console.log('使用指纹/面容验证')
      // 显示加载状态
      this.loading = true
      
      // 模拟验证过程
      setTimeout(() => {
        this.loading = false
        // 验证成功，进入支付流程
        this.verifyPaymentSuccess()
      }, 1500)
    },
    
    // 验证支付密码
    verifyPaymentPassword() {
      if (!this.paymentPassword) {
        alert('请输入支付密码')
        return
      }
      
      // 显示加载状态
      this.loading = true
      
      // 模拟密码验证过程
      setTimeout(() => {
        this.loading = false
        // 验证成功，进入支付流程
        this.verifyPaymentSuccess()
      }, 1000)
    },
    
    // 验证成功后的处理
    verifyPaymentSuccess() {
      // 隐藏验密界面
      this.showPasswordVerification = false
      
      // 开始实际支付流程
      this.startPayment()
    },
    
    // 发起支付 - 增加支付方式参数
    async startPayment() {
      this.paymentSuccess = false
      this.paymentFailed = false
      this.showQRCode = false
      
      try {
        // 真实API调用 - 使用封装的API方法
        // 传递群信息、金额和支付方式到后端
        const response = await createWechatPayment({
          orderId: this.orderId,
          groupId: this.paymentInfo.groupId,
          amount: this.paymentInfo.amount,
          groupName: this.paymentInfo.groupName,
          paymentMethod: this.selectedPaymentMethod // 添加支付方式参数
        })
        
        // 检查响应数据格式是否正确
        if (!response || typeof response !== 'object') {
          throw new Error('无效的响应数据')
        }
        
        const { code_url } = response
        if (code_url) {
          this.paymentLink = code_url
          this.showQRCode = true
          
          // 确保DOM更新后再生成二维码
          this.$nextTick(() => {
            this.generateQRCode()
          })
          
          // 开始倒计时
          this.startCountDown()
          
          // 轮询检查支付状态
          this.startCheckPaymentStatus()
        } else {
          throw new Error('未获取到支付链接')
        }
      } catch (error) {
        console.error('获取支付参数失败:', error)
        this.paymentFailed = true
      } finally {
        this.loading = false
      }
    },
    
    // 生成二维码
    async generateQRCode() {
      // 清空之前的二维码
      const canvas = this.$refs.qrCodeCanvas
      if (!canvas) {
        console.error('未找到canvas元素')
        this.paymentFailed = true
        this.showQRCode = false
        return
      }
      
      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      
      try {
        // 使用Promise版本的toCanvas方法，更便于错误处理
        await QRCode.toCanvas(canvas, this.paymentLink, {
          width: 200,
          height: 200,
          margin: 1,
          color: {
            dark: '#000000',
            light: '#ffffff'
          }
        })
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.paymentFailed = true
        this.showQRCode = false
      }
    },
    
    // 开始倒计时
    startCountDown() {
      this.countDown = 180
      // 清除之前的定时器
      if (this.timer) {
        clearInterval(this.timer)
      }
      this.timer = setInterval(() => {
        this.countDown--
        if (this.countDown <= 0) {
          clearInterval(this.timer)
          this.showQRCode = false
          this.paymentFailed = true
        }
      }, 1000)
    },
    
    // 修改此方法以适应新的参数格式
    startCheckPaymentStatus() {
      // 清除之前的定时器
      if (this.checkPaymentInterval) {
        clearInterval(this.checkPaymentInterval)
      }
      
      // 每3秒检查一次支付状态
      this.checkPaymentInterval = setInterval(async () => {
        try {
          // 真实API调用 - 使用封装的API方法
          const response = await queryPaymentStatus({
            orderId: this.orderId,
            groupId: this.paymentInfo.groupId
          })
          
          if (!response || typeof response !== 'object') {
            throw new Error('无效的支付状态响应')
          }
          
          const { status } = response
          
          if (status === 'SUCCESS') {
            // 支付成功
            clearInterval(this.checkPaymentInterval)
            this.showQRCode = false
            this.paymentSuccess = true
            // 如果有倒计时定时器，也清除
            if (this.timer) {
              clearInterval(this.timer)
            }
          } else if (status === 'FAILED') {
            // 支付失败
            clearInterval(this.checkPaymentInterval)
            this.showQRCode = false
            this.paymentFailed = true
          }
          // 其他状态（如处理中）继续轮询
        } catch (error) {
          console.error('检查支付状态失败:', error)
        }
      }, 3000)
    },
    
    // 重新支付
    retryPayment() {
      this.showPaymentConfirm = true
      this.showQRCode = false
      this.paymentFailed = false
      this.selectedPaymentMethod = 'wechat_balance' // 重置支付方式为默认
    },
    
    // 格式化当前时间
    formatCurrentTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    // 完成支付，返回到商户网页 - 修改为服务商模式
    completePayment() {
      // 这里可以根据业务需求决定返回哪个页面
      // 例如返回首页
      this.$router.push('/')
      // 或者返回上一页
      // this.$router.back()
    },
    
    // 查看订单详情
    viewOrderDetails() {
      // 这里可以跳转到订单详情页面
      // 目前只是打印信息，实际项目中应该跳转到相应页面
      console.log('查看订单详情', {
        orderId: this.orderId,
        groupId: this.paymentInfo.groupId,
        amount: this.paymentInfo.amount
      })
      alert('订单详情功能待实现')
    },
  }
}
</script>

<style scoped>
.payment-container {
  text-align: center;
  padding: 20px;
}

/* 支付确认界面样式 */
.payment-confirm {
  max-width: 400px;
  margin: 0 auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.payment-confirm h2 {
  color: #333;
  margin-bottom: 20px;
}

.payment-info {
  text-align: left;
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
}

.value {
  color: #333;
  font-weight: 500;
}

.value.amount {
  color: #f5222d;
  font-size: 18px;
  font-weight: bold;
}

.confirm-actions {
  display: flex;
  justify-content: space-between;
}

.cancel-btn,
.confirm-btn {
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  border: none;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #333;
}

.confirm-btn {
  background-color: #1890ff;
  color: white;
}

.qr-code-wrapper {
  display: inline-block;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 20px 0;
}

.payment-method-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-method-item:hover {
  border-color: #07c160;
}

.payment-method-item.selected {
  border-color: #07c160;
  background-color: #f0f9f4;
}

.method-icon {
  font-size: 24px;
  margin-right: 10px;
}

.method-name {
  flex: 1;
  text-align: left;
  font-size: 16px;
}

.selected-icon {
  color: #07c160;
  font-weight: bold;
  font-size: 18px;
}

/* 验密界面样式 */
.password-verification {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.verification-info {
  text-align: left;
  margin: 20px 0;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

.verification-info p {
  margin: 8px 0;
}

.password-input-container {
  margin: 20px 0;
}

.password-input-container input {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  box-sizing: border-box;
}

.verification-options {
  margin-top: 20px;
}

.fingerprint-btn {
  background: none;
  border: none;
  color: #07c160;
  font-size: 16px;
  cursor: pointer;
  padding: 10px;
}

/* 通用按钮样式 */
.confirm-actions,
.method-actions,
.verification-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
  gap: 15px;
}

.cancel-btn {
  flex: 1;
  padding: 12px;
  border: 1px solid #dcdcdc;
  background: #fff;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
}

.confirm-btn {
  flex: 1;
  padding: 12px;
  background: #07c160;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
}

.confirm-btn:hover {
  background: #06ad56;
}

.qr-code-wrapper {
  display: inline-block;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.payment-details {
  margin-top: 15px;
  text-align: left;
}

.payment-details p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.tip {
  margin-top: 15px;
  font-size: 16px;
  color: #333;
}

.expire-tip {
  color: #f37b1d;
  margin-top: 10px;
  font-size: 14px;
}

.success-message, .fail-message, .loading-message {
  padding: 30px 0;
}

.icon-success {
  display: inline-block;
  width: 60px;
  height: 60px;
  background-color: #52c41a;
  border-radius: 50%;
  line-height: 60px;
  color: white;
  font-size: 30px;
}

.icon-fail {
  display: inline-block;
  width: 60px;
  height: 60px;
  background-color: #f5222d;
  border-radius: 50%;
  line-height: 60px;
  color: white;
  font-size: 30px;
}

.success-message p, .fail-message p, .loading-message p {
  margin-top: 20px;
  font-size: 18px;
}

.fail-message button {
  margin-top: 20px;
  padding: 8px 20px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 微信风格的支付成功页面 */
.wechat-success-page {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  animation: successFadeIn 0.5s ease-out;
}

@keyframes successFadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.success-icon-container {
  width: 80px;
  height: 80px;
  margin: 30px auto;
  background-color: #07c160;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-success {
  color: #fff;
  font-size: 48px;
  font-weight: bold;
}

.success-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
}

.success-info {
  margin: 30px 0;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.payment-amount {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.payment-merchant,
.payment-method-info {
  text-align: left;
  margin-bottom: 20px;
}

.payment-merchant p,
.payment-method-info p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
}

.complete-button {
  width: 100%;
  padding: 15px;
  background: #07c160;
  color: #fff;
  border: none;
  border-radius: 25px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  margin-bottom: 20px;
}

.complete-button:hover {
  background: #06ad56;
}

.order-detail-btn {
  color: #999;
  font-size: 14px;
  cursor: pointer;
  padding: 10px;
}

.order-detail-btn:hover {
  color: #666;
}
</style>
